package com.usooft.metaTalent.core.system.service.basic;

import com.usooft.metaTalent.core.system.entity.Employee;
import com.usooft.metaTalent.core.system.entity.EmployeeWxOpenUser;
import com.usooft.metaTalent.core.system.query.EmployeeWxOpenUserQuery;
import com.usooft.metaTalent.core.system.service.EmployeeWxOpenUserService;
import com.usooft.metaTalent.core.system.service.base.BaseEmployeeWxOpenUserService;
import com.usooft.metaTalent.core.wx.entity.WxOpenUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

import static com.usooft.framework.core.utils.Checks.check;
import static com.usooft.framework.core.utils.Checks.checkNotNull;

@Service
@RequiredArgsConstructor
public class BasicEmployeeWxOpenUserService extends BaseEmployeeWxOpenUserService implements EmployeeWxOpenUserService {

    @Override
    public Optional<EmployeeWxOpenUser> findByWxOpenUser(WxOpenUser wxOpenUser) {
        return findOne(EmployeeWxOpenUserQuery.Filter.builder()
                .wxOpenUserIdIs(wxOpenUser.getId())
                .build());
    }

    @Override
    @Transactional
    public EmployeeWxOpenUser create(Employee employee, WxOpenUser wxOpenUser) {
        checkNotNull(employee, "必须提供员工");
        checkNotNull(wxOpenUser, "必须提供微信开放平台用户");
        check(!exists(employee), "账号已绑定其他微信");
        check(!exists(wxOpenUser), "该微信已绑定其他账号");
        return internalAdd(employee, wxOpenUser.getUserId());
    }

    private boolean exists(WxOpenUser wxOpenUser) {
        return count(EmployeeWxOpenUserQuery.Filter.builder()
                .wxOpenUserIdIs(wxOpenUser.getId())
                .build()) > 0;
    }

    private boolean exists(Employee employee) {
        return count(EmployeeWxOpenUserQuery.Filter.builder()
                .employeeIdIs(employee.getId())
                .build()) > 0;
    }

    // region 自动生成
    // endregion
}